package com.qq.weixin.mp.message.hxexp.service.impl;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.hxexp.weixin.common.jaxb.JaxbMarshallerHelper;
import com.hxexp.weixin.common.jaxb.JaxbUnmarshallerHelper;
import com.qq.weixin.constant.AutoReplyKeywords;
import com.qq.weixin.constant.MsgType;
import com.qq.weixin.mp.message.hxexp.model.receive.BaseMsgJaxb;
import com.qq.weixin.mp.message.hxexp.model.receive.MenuEventJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.TextReplyJaxb;
import com.qq.weixin.mp.message.hxexp.service.ClickEventService;

/**
 * 点击菜单拉取消息事件服务实现类
 * @author li.jiang
 *
 */
@Service
public final class ClickEventServiceImpl implements ClickEventService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClickEventServiceImpl.class);
    @Value("${kf.menu.msg}")
    private String kfMenuMsg;
    /* (non-Javadoc)
     * @see com.hxexp.weixin.pubac.reply.service.ClickEventService#receiveAndReply(java.lang.String)
     */
    @Override
    public String receiveAndReply(String xmlMsg) throws JAXBException, IOException {
        String replyXML = "";
        MenuEventJaxb menuEvent = (MenuEventJaxb) JaxbUnmarshallerHelper.unmarshal(new StringReader(xmlMsg),
                new Class<?>[] { BaseMsgJaxb.class, MenuEventJaxb.class });
        LOGGER.debug("接收到的消息已转换成对象: {}", menuEvent.toString());

        if (AutoReplyKeywords.KFZX.equals(menuEvent.getEventKey())) {
            TextReplyJaxb replyMsg = new TextReplyJaxb();
            replyMsg.setToUserName(menuEvent.getFromUserName());
            replyMsg.setFromUserName(menuEvent.getToUserName());
            replyMsg.setCreateTime(System.currentTimeMillis());
            replyMsg.setMsgType(MsgType.TEXT);
            replyMsg.setContent(kfMenuMsg);
            replyXML = JaxbMarshallerHelper.marshalToString(replyMsg);
        } else if ("notice".equals(menuEvent.getEventKey())) {
            // todo something // NOSONAR
        }
        return replyXML;
    }

}
